package com.qf.myInterceptor;

import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;

/**
 * Created by 54110 on 2021/6/22.
 */
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 执行方法之前进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入了拦截器");
        //验证用户是否登录 如果登录的情况下继续执行代码，如果未登录，则拦截题时用户需要登录
        Cookie[] cookies = request.getCookies();
        String token =null;
        if (cookies!=null&&cookies.length>0){
            for (Cookie cook:cookies
                    ) {
                if (cook.getName().equals("token")){
                    token = cook.getValue();
                }
            }

        }
        if (StringUtils.isEmpty(token)){
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.getWriter().write("用户未登录");
            return false;
        }
        return true;

    }

    /**
     * 方法执行完成后，进行拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }
}

